import { Component, input, Input, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalModule, NzModalRef } from 'ng-zorro-antd/modal';

import { DownloadProgress, DownloadService } from '../downloadService';

@Component({
  selector: 'download-service-modal',
  standalone: true,
  imports: [],
  template: `
    <ng-container>
      <div style="width: 100%; height: 20px; background-color: #f0f0f0; border-radius: 10px; overflow: hidden">
        <div
          style="height: 100%; background-color: #007bff; transition: width 0.3s ease"
          [style.width.%]="downloadProgress?.progress ?? 0"
        ></div>
      </div>
      @if (downloadProgress?.total) {
        <p>进度: {{ downloadProgress?.progress }}%</p>
        <p>
          已下载: {{ ((downloadProgress?.loaded ?? 0) / 1024 / 1024).toFixed(2) }} MB /
          {{ ((downloadProgress?.total ?? 0) / 1024 / 1024).toFixed(2) }} MB
        </p>
      } @else {
        <p>进度: {{ downloadProgress?.progress }}KB</p>
      }
    </ng-container>
  `,
  styles: [
    `
      button {
        margin-right: 8px;
      }
    `
  ]
})
export class NzDownloadModalComponent implements OnInit {
  downloadProgress?: DownloadProgress;
  isDownloading = false;

  filename!: string;
  url!: string;
  constructor(
    private downloadService: DownloadService,
    private msg: NzMessageService,
    private modal: NzModalRef
  ) {}
  ngOnInit(): void {
    debugger;
    if (!this.url || !this.filename) {
      this.msg.error('参数错误');
      this.close();
    } else {
      this.download();
    }
  }

  download() {
    debugger;

    this.isDownloading = true;
    this.downloadService.downloadFile(this.url, this.filename).subscribe({
      next: progress => {
        this.downloadProgress = progress;
        if (progress.status === 'completed') {
          this.isDownloading = false;
          console.log('文件下载完成');
          this.msg.success('文件下载成功！');
          this.close();
        }
      },
      error: error => {
        this.isDownloading = false;
        console.error('下载失败:', error);
        this.msg.error('下载失败');
        this.close();
      }
    });
  }

  close() {
    this.modal.destroy();
  }
}
